package com.jin.webvideo.base.dc;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态java脚本类加载器，保证本类加载器加载的class，在gc时会被卸载
 * @author biao532
 * @date 2023/12/02 21:42
 **/
class DynamicCompilationClassLoader extends ClassLoader {
    private Map<String, MemoryFileManager.OutputMemoryJavaFileObject> classMap;
    protected DynamicCompilationClassLoader(String name, ClassLoader parent) {
        super(name, parent);
        this.classMap = new HashMap<>();
    }

    void register(MemoryFileManager.OutputMemoryJavaFileObject fileObject) {
        classMap.put(fileObject.getName(), fileObject);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            return super.findClass(name);
        }
        catch (ClassNotFoundException e) {

        }
        if (!classMap.containsKey(name)) {
            throw new ClassNotFoundException(name);
        }

        try(InputStream stream = classMap.get(name).openInputStream()) {
            // 白名单校验
            Verifier.whiteList(stream, name);
            byte[] bs = classMap.get(name).getBytes();
            return defineClass(name, bs, 0, bs.length);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException(e.getMessage());
        }
    }
}
